package com.swgk.core.dialog;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.swgk.core.R;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.databinding.DialogImagesPreviewBinding;


import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 3/4/21 5:33 PM
 * @Description: 图片预览弹窗
 */
public class ImagesPreviewDialog extends DialogFragment {
    private DialogImagesPreviewBinding binding;

    public static ImagesPreviewDialog newInstance(String... urls) {
        ArrayList<String> list = new ArrayList<>();
        if (urls != null && urls.length > 0) {
            list.addAll(Arrays.asList(urls));
        }
        return newInstance(list, 0);
    }

    public static ImagesPreviewDialog newInstance(ArrayList<String> urls, int position) {
        Bundle args = new Bundle();
        args.putStringArrayList(RouterKey.DATA, urls);
        args.putInt(RouterKey.INT, position);
        ImagesPreviewDialog fragment = new ImagesPreviewDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.dialog_images_preview, null, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initPager();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getDialog() == null || getDialog().getWindow() == null) {
            return;
        }
        //设置dialog全屏
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.gravity = Gravity.CENTER;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
    }

    private void initPager() {
        if (getArguments() == null) return;
        List<String> urls = getArguments().getStringArrayList(RouterKey.DATA);
        int index = getArguments().getInt(RouterKey.INT, 0);
        if (urls == null) return;
        if (urls.size() == 1) {
            binding.tvImagePreviewNumber.setVisibility(View.GONE);
        } else {
            binding.tvImagePreviewNumber.setVisibility(View.VISIBLE);
            binding.tvImagePreviewNumber.setText(String.format("%s/%s", index + 1, urls.size()));
        }
        PhotoAdapter adapter = new PhotoAdapter(getContext(), urls);
        binding.vpImagePreview.setAdapter(adapter);
        binding.vpImagePreview.setCurrentItem(index);
        binding.vpImagePreview.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                binding.tvImagePreviewNumber.setText(String.format("%s/%s", position + 1, urls.size()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    /**
     * 展示弹窗
     */
    public void show(Context context) {
        if (context instanceof AppCompatActivity) {
            FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
            show(fragmentManager, "imagePreview");
        }
    }

    /**
     * 图片列表
     */
    private class PhotoAdapter extends PagerAdapter implements View.OnClickListener {

        private final Context context;
        private final List<String> imgUrl;

        public PhotoAdapter(Context context, List<String> imgUrl) {
            this.context = context;
            this.imgUrl = imgUrl;
        }

        @Override
        public int getCount() {
            return imgUrl == null ? 0 : imgUrl.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NotNull
        @Override
        public Object instantiateItem(@NotNull ViewGroup container, int position) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_images_preview, null);
            PhotoView phoneView = view.findViewById(R.id.photo_view);
            phoneView.enable();
            phoneView.setOnClickListener(this);
            RequestOptions options = new RequestOptions()
                    .fitCenter();
            Glide.with(context)
                    .load(imgUrl.get(position))
                    .apply(options)
                    .into(phoneView);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NotNull Object object) {
            container.removeView((View) object);
        }

        @Override
        public void onClick(View v) {
            dismiss();
        }
    }
}
